package com.wechat.api;

import static com.wechat.api.URLPool.*;

import java.util.Map;

import org.javatuples.Pair;

import com.google.common.collect.Maps;
import com.util.file.FileExtensionUtil;
import com.util.https.HttpsUtil;
import com.wechat.data.WebAccessToken;
import com.wechat.data.WechatEnv;
import com.wechat.data.user.UserInfo;

import jodd.http.HttpRequest;
import jodd.http.HttpResponse;

public final class WechatAPI extends AbstractWechatAPI {

	public WechatAPI(WechatEnv wechatEnv, boolean innerRefresh) {
		super(wechatEnv, innerRefresh);
	}

	/**
	 * 获取用户信息
	 */
	public UserInfo getUserInfo(String openid) {
		Map<String, String> params = Maps.newLinkedHashMap();
		params.put("access_token", accessToken.getAccess_token());
		params.put("openid", openid);
		params.put("lang", "zh_CN");
		return HttpsUtil.get(USER_INFO, params, UserInfo.class);
	}

	/**
	 * 换取网页授权access_token
	 */
	public WebAccessToken getWebAccessToken(String code) {
		Map<String, String> params = Maps.newLinkedHashMap();
		params.put("appid", wechatEnv.getAppid());
		params.put("secret", wechatEnv.getAppsecret());
		params.put("code", code);
		params.put("grant_type", "authorization_code");
		return HttpsUtil.get(URLPool.WEB_ACCESS_TOKEN, params, WebAccessToken.class);
	}

	/**
	 * 下载多媒体文件
	 */
	public Pair<byte[], String> download(String media_id) {
		Map<String, String> queryMap = Maps.newLinkedHashMap();
		queryMap.put("access_token", this.accessToken.getAccess_token());
		queryMap.put("media_id", media_id);
		HttpResponse response = HttpRequest.get(URLPool.DOWNLOAD).query(queryMap).send();
		return Pair.with(response.bodyBytes(), FileExtensionUtil.getExtension(response.mediaType()));
	}

}
